# -*- coding: utf-8 -*-
# @Date     :5/9/21 4:00 PM
# @Author   :xuhe
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class BossproPipeline:
    fp = None

    def open_spider(self, spider):
        print("开始爬虫....")
        self.fp = open('../招聘信息/美术招聘信息.txt', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        job_name = item['job_name']
        job_company = item['job_company']
        wage = item['wage']
        position = item['position']
        job_info = item['job_info']
        job_desc = item['job_desc']
        self.fp.write(
            job_name + '|' + job_company + '|' + wage + '|' + position + '|' + job_info + '\n' + job_desc + '\n')
        return item  # 传递给下一个即将被执行的管道类

    def close_spider(self, spider):
        print("结束爬虫！")
        self.fp.close()


class mysqlPipeline(object):
    conn = None
    cursor = None

    def open_spider(self, spider):
        self.conn = pymysql.Connect(host='127.0.0.1', port=3306, user='root', password='123', db='liepinTest',
                                    charset='utf8')

    def process_item(self, item, spider):
        self.cursor = self.conn.cursor()
        try:
            self.cursor.execute('CREATE TABLE  IF NOT EXISTS 美术 LIKE c')
            self.cursor.execute('insert into 美术 values("%s","%s","%s","%s","%s","%s")' % (
                item["job_name"], item['job_company'], item['wage'], item['position'], item['job_info'],
                item['job_desc']))
            self.conn.commit()
        except Exception as e:
            print(e)
            self.conn.rollback()
        return item

    def close_spider(self, spider):
        self.cursor.close()
        self.conn.close()
